<?php

namespace app\api\controller\mycurrency;

use addons\mycurrency\library\Common;
use addons\mycurrency\library\ThirdLogin;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\mycurrency\AgentApply;
use app\common\model\mycurrency\UserFeedback;
use app\common\model\mycurrency\UserFeedbackType;
use app\common\model\mycurrency\UserMoneyLog;
use app\common\model\mycurrency\UserRechargeOrder;
use app\common\model\mycurrency\UserRechargePackage;
use fast\Random;
use think\Config;
use think\Exception;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['wechatMiniLogin','wechatPhoneNumber','alipayMiniLogin','alipayPhoneNumber'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 微信授权登录
    */
    public function wechatMiniLogin()
    {
        $param = $this->request->param();
        $rule = [
            ['code', 'require', '请填写授权code']
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        try {
            $userInfo = ThirdLogin::wechatMiniLogin($param['code'],$param['pid']);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $isBindMobile = 'yes';
        if (empty($userInfo['mobile'])) {
            $isBindMobile = 'no';
        }
        $this->success('登录成功', ['token' => $userInfo['token'],'id' => $userInfo['id'], 'is_bind_mobile' => $isBindMobile]);
    }

    /**
     * 微信完善手机号
    */
    public function wechatPhoneNumber(){
        $param = $this->request->param();
        $rule = [
            ['encryptedData', 'require', 'encryptedData不能为空'],
            ['iv', 'require', 'iv不能为空'],
            ['token', 'require', 'token不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        //初始化
        $this->auth->init($param['token']);
        try {
            $config = config('wechatandalipay');
            //获取手机号
            $phone = \app\common\model\mycurrency\User::decryptData($config['wechat_miniapp']['appid'], $this->auth->wechat_session_key, $param['encryptedData'], $param['iv']);
            $user_id = ThirdLogin::bindingPhone($this->auth->id,$phone,'wechat');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        //模拟登陆
        $res = $this->auth->direct($user_id);
        $this->success('',$this->auth->getUserinfo());
    }



    /**
     * 支付宝授权登陆
    */
    public function alipayMiniLogin()
    {
        $param = $this->request->param();
        $rule = [
            ['code', 'require', '请填写授权code']
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        try {
            $userInfo = ThirdLogin::alipayMiniLogin($param['code'],$param['pid']);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $isBindMobile = 'yes';
        if (empty($userInfo['mobile'])) {
            $isBindMobile = 'no';
        }
        $this->success('登录成功', ['token' => $userInfo['token'],'id' => $userInfo['id'], 'is_bind_mobile' => $isBindMobile]);
    }

    /**
     * 支付宝完善手机号
     */
    public function alipayPhoneNumber(){
        $param = $this->request->param();
        $rule = [
            ['encryptedData', 'require', 'encryptedData不能为空'],
//            ['iv', 'require', 'iv不能为空'],
            ['token', 'require', 'token不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        //初始化
        $this->auth->init($param['token']);
        $config = config('wechatandalipay')['alipay'];
        $encryptedData = $param['encryptedData'];
        $result = ThirdLogin::decryptData($encryptedData, $config['apiSecret']);
        $result = json_decode($result, true);
        if(!$result){
            $this->error('获取手机号失败');
        }
        $phone = $result['mobile'];
        try {
            $user_id = ThirdLogin::bindingPhone($this->auth->id,$phone,'alipay');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        //模拟登陆
        $res = $this->auth->direct($user_id);
        $this->success('',$this->auth->getUserinfo());
    }








    /**
     * 获取会员信息
     */
    public function information()
    {
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $data['userinfo']['avatar_http'] = Common::GetHost() . $data['userinfo']['avatar'];
        $this->success('', $data);
    }

    /**
     * 用户意见反馈 - 问题类型
     */
    public function feedbackType(){
        $where = [
            'deletetime' => null
        ];
        $data = UserFeedbackType::where($where)->column('name');
        $this->success('',$data);
    }

    /**
     * 用户意见反馈 - 用户提交意见反馈
     */
    public function feedback(){
        $param = $this->request->param();
        $rule = [
            ['fullname', 'require', '姓名不能为空'],
            ['phone', ['require','/^1[3-9]\d{9}$/'], ['手机号不能为空','手机号格式不正确']],
            ['problemtype', 'require', '问题类型不能为空'],
            ['content', 'require', '反馈类型不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $increase = [
            'user_id' => $this->auth->id,
            'fullname' => $param['fullname'],
            'phone' => $param['phone'],
            'problemtype' => $param['problemtype'],
            'content' => $param['content'],
            'images' => $param['images'],
            'status' => UserFeedback::STATUS_WEIHUEIFU,
            'createtime' => time(),
        ];
        $res = UserFeedback::create($increase);
        if(!$res){
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * 余额 - 充值 - 充值套餐
    */
    public function rechargePackage(){
        $data = UserRechargePackage::where(['status' => UserRechargePackage::STATUS_ZHENGCHANG,'deletetime' => null])->field('id,recharge_fee,give_fee')->select();
        $this->success('',$data);
    }

    /**
     * 余额 - 充值 - 发起充值
    */
    public function rechargeOrder(){
        $param = $this->request->param();
        if($param['package_id'] == null && $param['recharge_fee'] == null){
            $this->error('请选择充值套餐或输入充值金额');
        }
        $increase = [
            'user_id' => $this->auth->id,
            'package_id' => $param['package_id'],
            'order_sn' => UserRechargeOrder::getOrderSn(),
            'status' => UserRechargeOrder::STATUS_WEIZHIFU,
            'placetime' => time(),
            'createtime' => time(),
        ];

        if($param['package_id'] != null){
            $package = UserRechargePackage::where(['id' => $param['package_id'], 'deletetime' => null])->find();
            if(!$package){
                $this->error('充值套餐不存在');
            }
            if($package['status'] != UserRechargePackage::STATUS_ZHENGCHANG){
                $this->error('充值套餐不可用');
            }
            $increase['recharge_fee'] = $package['recharge_fee'];
            $increase['give_fee'] = $package['give_fee'];
        }else{
            $increase['recharge_fee'] = $param['recharge_fee'];
        }
        $increase['payment_fee'] = $increase['recharge_fee'];
        $order = UserRechargeOrder::create($increase);
        if(!$order){
            $this->error('下单失败');
        }
        $this->success('下单成功',[
            'recharge_order_id' => $order->id,
        ]);
    }

    /**
     * 余额 - 充值 - 充值订单详情
    */
    public function rechargeOrderInfo(){
        $param = $this->request->param();
        $rule = [
            ['recharge_order_id', 'require', '余额充值记录id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $info = UserRechargeOrder::where(['id' => $param['recharge_order_id'],'deletetime' => null])->find();
        if (!$info){
            $this->error('充值记录不存在');
        }
        $this->success('加载成功',$info);
    }

    /**
     * 余额 - 变动记录
    */
    public function moneyLog(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'user_id' => $this->auth->id,
        ];

        $list = UserMoneyLog::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('id,money,memo,type,createtime')
            ->select();
        foreach($list as $k => $v){
            if($list[$k]['type'] == UserMoneyLog::TYPE_TIXIAN || $list[$k]['type'] == UserMoneyLog::TYPE_HOUTAIJIASHAO){//
                $list[$k]['money'] = '-' . $list[$k]['money'];
            }

        }
        $num = UserMoneyLog::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }





    /**
     * 获取微信支付宝配置
     */
    private static function getWechatAndAlipayConfig()
    {
        $config = config('wechatandalipay');
        return $config;
    }

}
